<template>
  <el-main>
    <el-card shadow="never" class="chat_content" ref="scrollable">
      <el-tabs tab-position="top">
        <el-tab-pane label="Chat">
          <el-card v-for="item in chatGpts" :key="item.id" class="box-card" style="box-shadow: none; margin-top: 10px">
            <template #header v-if="item.type == 'question'">
              <div class="card-header" style="text-align: right">
                <span>{{ item.content }}</span>
              </div>
            </template>

            <div v-if="item.type == 'answer'">
              <el-card shadow="always" v-show="item.content != ''" style="border: 0">
                <v-md-preview :text="item.content"></v-md-preview>
              </el-card>
              <!-- {{ item.content }} -->
            </div>
          </el-card>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <el-card class="chatInput_box">
      <el-form ref="form" :model="sys" label-width="100px" style="margin-top: 20px">
        <el-form-item label="">
          <el-col :span="22">
            <el-input type="textarea" :autosize="{ minRows: 4 }" v-model="sys.message"></el-input>
          </el-col>
          <el-col :span="2">
            <el-button type="primary" :loading="chatLoading" @click="publish" @keydown.enter="publish()">发送</el-button>
          </el-col>
        </el-form-item>
      </el-form>
    </el-card>
  </el-main>
</template>

<script>
// 预览组件以及样式
import VMdPreview from '@kangc/v-md-editor/lib/preview';
import '@kangc/v-md-editor/lib/style/preview.css';
// VuePress主题以及样式（这里也可以选择github主题）
import vuepressTheme from '@kangc/v-md-editor/lib/theme/vuepress.js';
import '@kangc/v-md-editor/lib/theme/style/vuepress.css';
// Prism
import Prism from 'prismjs';
// 代码高亮
import 'prismjs/components/prism-json';

// import typeWriter from "../../../utils/typeWriter.js";
// 选择使用主题
VMdPreview.use(vuepressTheme, {
  Prism,
});
export default {
  name: 'system',
  components: {
    VMdPreview,
    vuepressTheme,
  },
  data() {
    return {
      sys: {
        message: '',
      },
      result: '',
      chatGpts: [],
      chatLoading: false,
    };
  },
  mounted() {
    //绑定监听事件
    // window.addEventListener("keydown", this.keyDown);
  },
  beforeUnmount() {
    //销毁事件
    // window.removeEventListener("keydown", this.keyDown, false);
  },
  methods: {
    keyDown(e) {
      if (e.keyCode == 13 || e.keyCode == 100) {
        this.publish();
      }
    },

    async publish() {
      if (this.chatLoading == true) return;

      this.chatLoading = true;
      var message = this.sys.message;
      const uniqueId = 'id-' + Math.random().toString(36).substr(2, 9);
      this.chatGpts.push({
        id: uniqueId,
        content: message,
        sourceId: '',
        type: 'question',
        role: 'user',
        // question: message,
      });
      const chatMessage = this.chatGpts.filter(x => x.type == 'question');

      await this.$API.open.chat.post(chatMessage, this.renderChat, this.successChat, this.errorChat);
    },
    renderChat(val) {
      const content = val
        .replace(/^data: /, '')
        ?.split('data:')
        ?.map(item => item.replace(/\n\n$/, ''))
        ?.slice(-1);

      if (content[0].indexOf('[DONE]') != -1) {
        return;
      }
      var data = JSON.parse(content[0]);

      var el = this.chatGpts.find(map => map.id == data.id);
      if (el == null) {
        el = {
          id: data.id,
          content: data.choices[0].message.content,

          type: 'answer',
        };
        this.chatGpts.push(el);
      } else {
        el.content += data.choices[0].message.content;
      }
    },
    successChat() {
      this.sys.message = '';
      this.chatLoading = false;
    },
    errorChat() {
      this.chatLoading = false;
      this.message.error('出现异常，请重试');
    },
  },
  watch: {
    chatGpts: {
      handler() {
        this.$nextTick(() => {
          // console.log("chat gpts is change");

          let x = document.getElementsByClassName('chat_content')[0];
          x.scrollTop = x.scrollHeight; //将滚轮置底
        });
      },
      immediate: true,
      deep: true,
    },
  },
};
</script>

<style>
.save-div {
}
.chatInput_box {
  position: fixed;
  bottom: 5em;
  width: 82%;
  /* line-height: var(--footer-height); */
}
.chat_content {
  max-height: calc(100vh - 306px);
  overflow: auto;
}
</style>
